package a51qindian.com.comprehensive.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.WithdrawVerifyAdapter;
import a51qindian.com.comprehensive.base.QDBaseFragment;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.WithDrawInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/21 0021
 * Description: 店铺提现申请审核界面
 */

public class WithdrawVerifyFragment extends QDBaseFragment {
    public static final String VERIFY_STATE = "verify_state";
    public static final String VERIFY_FINISHED = "1";
    public static final String VERIFY_UNFINISHED = "0";
    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    private WithdrawVerifyAdapter mAdapter;
    private List<WithDrawInfo> mWithDrawInfoList;
    private AlertDialog.Builder mBuilder;
    private static final String WITHDRAW_PASS = "1";
    private static final String WITHDRAW_REFUSED = "2";

    public static WithdrawVerifyFragment newInstance(String verifyState) {

        Bundle args = new Bundle();
        args.putString(VERIFY_STATE, verifyState);
        WithdrawVerifyFragment fragment = new WithdrawVerifyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_withdraw_verify;
    }

    private String mType;

    @Override
    protected void initSth() {
        super.initSth();
        mWithDrawInfoList = new ArrayList<>();
        mType = getArguments().getString(VERIFY_STATE, "");
        mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new WithdrawVerifyAdapter(mContext, mType);
        mRecycler.addItemDecoration(new LinearItemDecoration());
        mRecycler.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                showVerifyDialog("提示", "商铺提现审核", pos);
            }
        });
        setSmartRefreshLayout(mLayoutRefresh);

    }

    /**
     * 显示提现审核窗口
     *
     * @param title 标题
     * @param msg   消息
     * @param pos   位置  更新界面
     */
    private void showVerifyDialog(String title, String msg, final int pos) {
        if (mBuilder == null) {
            mBuilder = new AlertDialog.Builder(mContext)
                    .setTitle(title)
                    .setMessage(msg)
                    .setNegativeButton("拒绝提现", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            verifyApply(mUid, mWithDrawInfoList.get(pos).getWid(), WITHDRAW_REFUSED, pos);
                        }
                    })
                    .setPositiveButton("提现通过", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            verifyApply(mUid, mWithDrawInfoList.get(pos).getWid(), WITHDRAW_PASS, pos);

                        }
                    });
        } else {
            mBuilder.setTitle(title)
                    .setMessage(msg);
        }
        mBuilder.create().show();
    }

    /**
     * 提现处理
     *
     * @param uid    用户编号
     * @param wid    提现编号
     * @param status 状态  1：通过  2：拒绝
     * @param pos    位置   更新界面
     */
    private void verifyApply(String uid, String wid, String status, final int pos) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("wid", wid);
        map.put("status", status);
        ObservableHelper.createObservable(RetrofitCreator.createService().withdrawVerify(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            showToast(object.getString("info"));
                            if (object.getInt("code") == 1) {
                                mWithDrawInfoList.remove(pos);
                                mAdapter.notifyItemRemoved(pos);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showWithdrawList(mUid, mType, String.valueOf(mPage + 1));
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showWithdrawList(mUid, mType, "0");
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        if (mType.equals(VERIFY_UNFINISHED)) {
            showWithdrawList(SpUtil.getUserInfo(mContext, SpUtil.USER_ID), mType, "0");
        }
    }

    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        if (mType.equals(VERIFY_FINISHED)) {
            showWithdrawList(SpUtil.getUserInfo(mContext, SpUtil.USER_ID), mType, "0");
        }
    }

    /**
     * 显示提现记录列表
     *
     * @param uid  用户编号
     * @param type 类型  0：未完成，1：已完成
     */
    private void showWithdrawList(String uid, String type, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("status", type);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService()
                .withDrawList(map))
                .subscribe(new SelectorObserver<BaseModel<List<WithDrawInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<WithDrawInfo>> listBaseModel) {
                        List<WithDrawInfo> withDrawInfoList = listBaseModel.getData();
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage = 0;
                            mWithDrawInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh && withDrawInfoList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mWithDrawInfoList.addAll(withDrawInfoList);
                        mAdapter.setWithDrawInfoList(mWithDrawInfoList);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onFailure();
                        stopRefreshLoad();
                    }
                });

    }

}
